import React, { useCallback, useState, useEffect } from "react"
import { FormProps } from "@/components/modal/form.modal"
import { FormRender } from "@whzhuke/antd"
import useForm from "antd/es/form/hooks/useForm"
import contractService from "@/services/contract.service"
import { Button, Space } from "antd"

interface Props {
  values?: any
  // 可注入不同模块的发送服务，需包含 send 方法
  service?: { send: (params: any) => Promise<any> }
}
export const Sendcontracts: React.FC<Props & FormProps> = props => {
  const { values, onDone, service } = props
  const [form] = useForm<any>()
  const [supplierAccounts, setSupplierAccounts] = useState<any[]>([])
  const [loadingSuppliers, setLoadingSuppliers] = useState(false)
  const sendService = service?.send ?? contractService.send

  const getSupplierAccounts = useCallback(async (keyword?: string) => {
    try {
      setLoadingSuppliers(true)
      const res = await contractService.userCombo({
        keyword
      })
      const list = res?.data?.list ?? res?.data ?? []
      const accounts = list.map((item: any) => ({
        label: item.username ?? item.companyName ?? item.name ?? "",
        value: item.userId ?? item.id,
        raw: item
      }))
      setSupplierAccounts(accounts)
      return accounts
    } catch (error) {
      console.error("获取供应商账号失败:", error)
      setSupplierAccounts([])
      return []
    } finally {
      setLoadingSuppliers(false)
    }
  }, [])

  useEffect(() => {
    getSupplierAccounts()
  }, [getSupplierAccounts])

  const handleSupplierSearch = useCallback(
    (value: string) => {
      const keyword = value?.trim() || undefined
      getSupplierAccounts(keyword)
    },
    [getSupplierAccounts]
  )

  const onFinish = useCallback(
    (data: any) => {
      const payload = {
        id: values?.id ?? data.id,
        userId: data.userId,
        name: values?.name ?? data.name,
        code: values?.code ?? data.code
      }
      sendService(payload).then(() => onDone?.())
    },
    [values, onDone, sendService]
  )

  const handleCancel = useCallback(() => {
    onDone?.()
  }, [onDone])

  return (
    <FormRender
      form={form}
      initialValues={{}}
      layout="horizontal"
      preserve={false}
      onFinish={onFinish}
      labelCol={{ span: 8 }}
      wrapperCol={{ span: 16 }}
      style={{ width: 600 }}
      fieldList={[
        {
          fieldType: "select",
          formItemConfig: {
            required: true,
            name: "userId",
            label: "供应商账号"
          },
          config: {
            placeholder: "输入关键字搜索供应商登录账号",
            showSearch: true,
            optionFilterProp: "label",
            filterOption: false,
            options: supplierAccounts,
            loading: loadingSuppliers,
            onSearch: handleSupplierSearch
          }
        },
        {
          fieldType: "diy",
          formItemConfig: {
            wrapperCol: { offset: 8, span: 16 }
          },
          component: (
            <Space>
              <Button onClick={handleCancel}>取消</Button>
              <Button type="primary" htmlType="submit">
                确定
              </Button>
            </Space>
          )
        }
      ]}
      autoComplete="off"
    />
  )
}
